package com.mszlu.blog.handler;

import com.alibaba.fastjson.JSON;
import com.mszlu.blog.dao.pojo.SysUser;
import com.mszlu.blog.service.LoginService;
import com.mszlu.blog.utils.UserThreadLocal;
import com.mszlu.blog.vo.ErrorCode;
import com.mszlu.blog.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Package: com.mszlu.blog.handler
 * @ClassName: LoginIntercepter
 * @Author: 陈威
 * @CreateTime: 2021/8/31 16:00
 * @Description:
 */
@Component

public class LoginIntercepter implements HandlerInterceptor {
    @Autowired
    LoginService loginService;
    Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 描述：
         * @Author 陈威
         * 1.判断请求的接口路径是否为Handlermethod（controller方法）
         * 2.判断token是否为空 如果为空 未登录
         * 3.如果token不为空 登录验证loginservice checktoken
         * 4.如果认证成功 放行即可
         **/
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader("Authorization");

        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}", requestURI);
        log.info("request method:{}", request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");

        //如果为空 未登录
        if (StringUtils.isBlank(token)) {
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        //对token进行验证
        SysUser sysUser = loginService.checkToken(token);
        //如果未从redis中获取到数据 那么就是未登录
        if (sysUser == null) {
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }


        //向Threadlocal中存放用户信息
        UserThreadLocal.put(sysUser);
        //登录成功
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //如果不删除 Threadlocal中用完的信息，会有内存泄露的风险
        UserThreadLocal.remove();
    }
}